<template>
  <div class="app-container" style="padding: 0; margin: 0">
    <el-select
      class="main-select-tree"
      ref="selectTree"
      v-model="selectedSingleValue"
      clearable
      @clear="clearSelectInput"
    >
      <el-option
        v-for="item in formatData(dataTree)"
        :key="item.value"
        :label="item.name"
        :value="item.value"
        style="display: none"
      />
      <el-tree
        class="main-select-el-tree"
        ref="selectElTree"
        :data="dataTree"
        node-key="id"
        highlight-current
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="true"
        default-expand-all
        :filter-node-method="filterNode"
      />
    </el-select>
  </div>
</template>
<script>
export default {
  props: {
    selectedSingleValue: {
      type: String,
      default: "",
    },
    selectedSingleId: {
      type: String,
      default: "",
    },
    dataTree: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 递归遍历数据
    formatData(data) {
      let options = [];
      const formatDataRecursive = (data) => {
        data.forEach((item) => {
          options.push({ name: item.name, value: item.id });
          if (item.children && item.children.length > 0) {
            formatDataRecursive(item.children);
          }
        });
      };
      formatDataRecursive(data);
      return options;
    },
    // 点击事件
    handleNodeClick(node) {
      this.$refs.selectTree.blur();
      this.$emit("update:selectedSingleValue", node.name);
      this.$emit("update:selectedSingleId", node.id);
    },
    // 清空事件
    clearSelectInput() {
      // console.log(this.selectedSingleId, this.selectedSingleValue, "999999");
      this.$emit("update:selectedSingleValue", "");
      this.$emit("update:selectedSingleId", "");
      // 获取 el-tree 实例的引用
      const elTree = this.$refs.selectElTree;
      // 将当前选中的节点设置为 null
      elTree.setCurrentKey(null);
    },
  },
};
</script>
<style lang="scss" scoped>
// .main-select-tree {
//   width: 240px;
// }
.main-select-el-tree .el-tree-node .is-current > .el-tree-node__content {
  font-weight: bold;
  color: #409eff;
}
.main-select-el-tree .el-tree-node.is-current > .el-tree-node__content {
  font-weight: bold;
  color: #409eff;
}
</style>
